<?php
declare (strict_types = 1);

namespace app\controller\backend;

use app\exception\ModelException;
use app\model\RecycleBin;
use app\model\Tag;
use app\validate\TagValidate;
use Overtrue\Pinyin\Pinyin;
use think\exception\ValidateException;

class TagController extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     */
    public function index(Tag $tag): \think\response\Json
    {
        $websiteId = (int)input('param.website_id');
        if(!$websiteId){
            return jsonReturn(-1,'网站ID不能为空');
        }
        $lang = input('lang');
        if(empty($lang)){
            $lang = 'zh';
        }
        $limit = $this->setLimit();
        $title = input('title') ?: '';
        $where = [
            ['seller_id', '=' ,$this->admin['seller_id']],
            ['website_id' ,'=', $websiteId],
            ['lang','=',$lang],
            ['is_del','=',1],
        ];
        if($title){
            array_push($where,['title','like','%'.$title.'%']);
        }
        try{
            $tagList = $tag->where($where)->paginate($limit)->each(function(&$item){
                $contentNum = $item->subContent()->where('is_del',1)->count();
                $item -> article_count = $contentNum;
                $item -> save();
            });
            }catch(\Exception $e){
                throw new ModelException($e->getMessage());
            }
        return json(['code'=>0,'total'=>$tagList->total(),'msg'=>'success','data'=>$tagList->all()]);
    }

    /**
     * 保存新建的资源
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelNotUniqueException
     */
    public function save(Tag $tag): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            // 数据验证
            try{
                validate(TagValidate::class)->scene('save')->check($param);
            }catch(ValidateException $e){
                return jsonReturn(-1, $e->getError());
            }
            $param['seller_id'] = $this->admin['seller_id'];
            $param['unique_tag'] = $param['seller_id'] . '-' . $param['website_id'] . '-' . $param['lang'] .'-' . $param['title'];
            $tag->saveUnique(['unique_tag'=> $param['unique_tag'],'is_del'=>1],'标签名称已经存在');
            $pinyin = new Pinyin();
            $param['first_letter'] = strtoupper(substr($pinyin->abbr($param['title']),0,1));
            $param = $this->setSEO($param);
            $res = $tag -> addTag($param);
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * 保存更新的资源
     * @return \think\response\Json
     * @throws \app\exception\ModelException*@throws \app\exception\ModelNotUniqueException
     * @throws \app\exception\ModelNotUniqueException
     */
    public function update(Tag $tag): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            try {
                validate(TagValidate::class)->scene('update')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-1, $e->getError());
            }
            $where = [
                'id' => $param['id'],
                'seller_id' => $this->admin['seller_id'],
                'is_del' => 1,
            ];
            $param = $this->setSEO($param);
            $param['unique_tag'] = $this->admin['seller_id'] . '-' . $param['website_id'] . '-' . $param['lang'] .'-'. $param['title'];
            $tag->updateUnique(['unique_tag' => $param['unique_tag']],$param['id'],'标签名称已经存在');
            $pinyin = new Pinyin();
            $param['first_letter'] = strtoupper(substr($pinyin->abbr($param['title']),0,1));
            $res = $tag -> updateTag($where,$param);
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * 删除指定资源
     *
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function delete(Tag $Tag,RecycleBin $recycleBin): \think\response\Json
    {
        if(request()->isPost()){
            $id = (int)input('id');
            if(!$id){
                return jsonReturn(-1,'标签ID不能为空');
            }
            $where = [
                'id' => $id,
                'seller_id' => $this->admin['seller_id'],
            ];
            $tag = $Tag->getTag($where)['data'];
            // 复制删除内容到回收站表
            $binData = [
                'seller_id' => $this->admin['seller_id'],
                'object_id' => $id,
                'sub_id' => '',
                'module_id' => '',
                'table_name' => 'tag',
                'title' => $tag['title'],
                'admin_id' => $this->admin['seller_id'],
                'name' => $this->admin['name'],
            ];
            $recycleBin -> addRecycleBin($binData);
            $res = $Tag -> softDelTag($where);
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * 配置SEO
     * @param $param
     * @return mixed
     */
    public function setSEO($param)
    {
        if(empty($param['seo_title'])){
            $param['seo_title'] = $param['title'];
        }
        if(empty($param['seo_keywords'])){
            $param['seo_keywords'] = $param['title'];
        }
        if(empty($param['seo_description'])){
            $param['seo_description'] = $param['title'];
        }
        return $param;
    }
}
